package com.fly.demo.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.demo.JsonResult;

import io.swagger.annotations.ApiOperation;

@RestController
public class TestController
{
    ObjectMapper mapper = new ObjectMapper();
    
    Resource resource = new ClassPathResource("easy-json-simple-0.0.1.jar");
    
    @ApiOperation("test")
    @GetMapping(value = "/test", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void test(HttpServletResponse response)
        throws IOException
    {
        // 返回json或application/octet-stream
        if (System.currentTimeMillis() % 2 == 0)
        {
            JsonResult<?> result = JsonResult.error("系统异常，请稍后重试!");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            response.getWriter().print(mapper.writeValueAsString(result));
            return;
        }
        response.setHeader("Content-Disposition", "attachment;filename=down.zip");
        try (InputStream is = resource.getInputStream(); OutputStream os = response.getOutputStream())
        {
            IOUtils.copy(is, os);
            os.flush();
        }
    }
}
